package com.cw.subject.domain.handler.subject;

import com.cw.subject.common.enums.SubjectInfoTypeEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 题目类型工厂
 * 将所有策略类加载至该工厂
 *
 * @author: 江传文
 * @date: 2024/4/12 16:50
 */
@Component
public class SubjectTypeHandlerFactory implements InitializingBean {

    // 注入四个策略类均实现的接口SubjectTypeHandler
    @Resource
    private List<SubjectTypeHandler> subjectTypeHandlerList;

    private final Map<SubjectInfoTypeEnum, SubjectTypeHandler> handlerMap = new HashMap<>();

    public SubjectTypeHandler getHandler(int subjectType) {
        SubjectInfoTypeEnum subjectInfoTypeEnum = SubjectInfoTypeEnum.getByCode(subjectType);
        return handlerMap.get(subjectInfoTypeEnum);
    }

    /* 实现InitializingBean接口后,Spring 容器在实例化 bean 并完成属性注入后,会调用 afterPropertiesSet() 方法,
        允许bean在初始化阶段执行自定义的初始化逻辑。*/
    @Override
    public void afterPropertiesSet() throws Exception {
        for (SubjectTypeHandler subjectTypeHandler : subjectTypeHandlerList) {
            handlerMap.put(subjectTypeHandler.getHandlerType(), subjectTypeHandler);
        }
    }
}